package com.mfhcd.facepay.utils;

import android.animation.Animator;
import android.app.Activity;
import android.content.Context;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;


import com.mfhcd.facepay.R;
import com.mfhcd.facepay.adapter.BottomPopupListAdapter;
import com.mfhcd.facepay.base.BaseActivity;
import com.mfhcd.facepay.base.NavigationController;
import com.mfhcd.facepay.listener.OnItemClickListener;
import com.mfhcd.facepay.model.PhotoBean;
import com.mfhcd.facepay.model.TypeModel;
import com.mfhcd.facepay.widget.CancelEditText;
import com.mfhcd.facepay.widget.RecycleViewDivider;
import com.mfhcd.facepay.widget.wheeldate.DateScrollerDialog;
import com.mfhcd.facepay.widget.wheeldate.listener.OnDateCustomListener;
import com.mfhcd.facepay.widget.wheeldate.listener.OnDateSetListener;

import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import per.goweii.anylayer.AnimatorHelper;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.DialogLayer;
import per.goweii.anylayer.Layer;

/**
 * @Author：张洪顺
 * @E-Mail: zhanghs@mfhcd.com
 * @Date：2019-09-25 14:29
 * @版权所有 © 现代金融控股（成都）有限公司
 * @描述：通用弹框工具类
 */
public class DialogUtils {
    private static DialogLayer mDialogLayer;

    /**
     * 加载提示框
     *
     * @param context
     */
    public static void showLoadingDialog(Context context) {
        showLoadingDialog(context, null);
    }

    /**
     * 加载提示框
     *
     * @param context
     * @param loadingMsg
     */
    public static void showLoadingDialog(Context context, String loadingMsg) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_loading)
                .gravity(Gravity.CENTER)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .show();
        ImageView imageView = mDialogLayer.getView(R.id.iv_loading);
        TextView textView = mDialogLayer.getView(R.id.tv_loading_text);
        // 加载动画
        Animation hyperspaceJumpAnimation = AnimationUtils.loadAnimation(context, R.anim.loading_animation);
        // 使用ImageView显示动画
        imageView.startAnimation(hyperspaceJumpAnimation);
        if (!TextUtils.isEmpty(loadingMsg)) {
            textView.setText(loadingMsg);
        }
    }

    /**
     * 确定按钮弹框
     *
     * @param context
     * @param title
     * @param msg
     */
    public static void showConfirmDialog(Context context, String title, String msg) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_confirm)
                .gravity(Gravity.CENTER)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .onClick((layer, v) -> {
                    layer.dismiss();
                }, R.id.tv_dialog_yes).show();
        TextView tvTitle = mDialogLayer.getView(R.id.tv_dialog_title);
        tvTitle.setText(title);
        if (TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.GONE);
        }
        TextView tvContent = mDialogLayer.getView(R.id.tv_dialog_content);
        if (!TextUtils.isEmpty(msg)) {
            tvContent.setText(msg);
        }
    }

    /**
     * 确定按钮弹框
     *
     * @param context
     * @param title
     * @param msg
     * @param listener
     */
    public static void showConfirmDialog(Context context, String title, String msg, DialogClickListener listener) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_confirm)
                .gravity(Gravity.CENTER)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .onClick((layer, v) -> {
                    layer.dismiss();
                    if (listener != null) {
                        listener.onConfirmClick(v);
                    }
                }, R.id.tv_dialog_yes).show();
        TextView tvTitle = mDialogLayer.getView(R.id.tv_dialog_title);
        tvTitle.setText(title);
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.GONE);
        }
        TextView tvContent = mDialogLayer.getView(R.id.tv_dialog_content);
        if (!TextUtils.isEmpty(msg)) {
            tvContent.setText(msg);
        }
    }

    /**
     * 确定按钮弹框，点击finish
     *
     * @param activity
     * @param title
     * @param msg
     */
    public static void showExitDialog(Activity activity, String title, String msg) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(activity);
        fitKeyboard(activity, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_confirm)
                .gravity(Gravity.CENTER)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .onClick((layer, v) -> {
                    layer.dismiss();
                    activity.finish();
                }, R.id.tv_dialog_yes).show();
        TextView tvTitle = mDialogLayer.getView(R.id.tv_dialog_title);
        tvTitle.setText(title);
        if (!TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.GONE);
        }
        TextView tvContent = mDialogLayer.getView(R.id.tv_dialog_content);
        if (!TextUtils.isEmpty(msg)) {
            tvContent.setText(msg);
        }
    }

    /**
     * 确定取消弹框
     *
     * @param context
     * @param title
     * @param content
     * @param listener
     */
    public static void showConfirmCancelDialog(Context context, String title, String content, String leftBtn, String rightBtn, DialogClickListener listener) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_normal)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .gravity(Gravity.CENTER)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .onClick((layer, v) -> {
                    layer.dismiss();
                    if (listener != null) {
                        listener.onCancelClick();
                    }
                }, R.id.tv_dialog_no)
                .onClick((layer, v) -> {
                    layer.dismiss();
                    if (listener != null) {
                        listener.onConfirmClick(v);
                    }
                }, R.id.tv_dialog_yes).show();
        TextView tvTitle = mDialogLayer.getView(R.id.tv_dialog_title);
        tvTitle.setText(title);
        if (TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.GONE);
        }
        TextView tvContent = mDialogLayer.getView(R.id.tv_dialog_content);
        tvContent.setText(content);
        TextView btnLeft = mDialogLayer.getView(R.id.tv_dialog_no);
        btnLeft.setText(leftBtn);
        TextView btnRight = mDialogLayer.getView(R.id.tv_dialog_yes);
        btnRight.setText(rightBtn);
    }

    /**
     * 确定取消弹框
     *
     * @param context
     * @param title
     * @param hint
     * @param listener
     */
    public static void showSingleEditDialog(Context context, String title, String hint, String leftBtn, String rightBtn, DialogClickListener listener) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_edit)
                .gravity(Gravity.CENTER)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .onClick((layer, v) -> {
                    layer.dismiss();
                    if (listener != null) {
                        listener.onCancelClick();
                    }
                }, R.id.tv_dialog_no)
                .onClick((layer, v) -> {
                    EditText editText = layer.getView(R.id.et_dialog_content);
                    String inputContent = editText.getText().toString();
                    if (TextUtils.isEmpty(inputContent)) {
                        Toast.makeText(context, "请输入" + title, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    v.setTag(inputContent);
                    layer.dismiss();
                    if (listener != null) {
                        listener.onConfirmClick(v);
                    }
                }, R.id.tv_dialog_yes).show();
        TextView tvTitle = mDialogLayer.getView(R.id.tv_dialog_title);
        tvTitle.setText(title);
        if (TextUtils.isEmpty(title)) {
            tvTitle.setVisibility(View.GONE);
        }
        CancelEditText editText = mDialogLayer.getView(R.id.et_dialog_content);
        editText.setHint(hint);
        TextView btnLeft = mDialogLayer.getView(R.id.tv_dialog_no);
        btnLeft.setText(leftBtn);
        TextView btnRight = mDialogLayer.getView(R.id.tv_dialog_yes);
        btnRight.setText(rightBtn);
    }

    /**
     * 底部弹窗展示公共菜单dialog
     *
     * @param lists
     * @param listener
     */
    public static void showBottomDialog(Context context, List<TypeModel> lists, OnItemClickListener listener) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(R.layout.layout_dialog_bottom)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .gravity(Gravity.BOTTOM)
                .contentAnimator(new DialogLayer.AnimatorCreator() {
                    @Override
                    public Animator createInAnimator(View content) {
                        return AnimatorHelper.createBottomInAnim(content);
                    }

                    @Override
                    public Animator createOutAnimator(View content) {
                        return AnimatorHelper.createBottomOutAnim(content);
                    }
                })
                .onClickToDismiss(R.id.tv_bottom_cancel)
                .show();
        BottomPopupListAdapter popupListAdapter = new BottomPopupListAdapter(lists);
        RecyclerView recyclerView = mDialogLayer.getView(R.id.rv_bottom_list);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(popupListAdapter);
        recyclerView.addItemDecoration(new RecycleViewDivider(
                context, LinearLayoutManager.HORIZONTAL, 1, context.getResources().getColor(R.color.color_EAEAEA)));
        popupListAdapter.setOnItemClickListener((adapter1, view, position) -> {
            mDialogLayer.dismiss();
            if (listener != null) {
                listener.onItemClick(position);
            }
        });
        int restrainHeight = AppUtils.getScreenHeight(context) / 5 * 3;
        LinearLayout contentView = (LinearLayout) mDialogLayer.getViewHolder().getContent();
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(() -> {
            if (contentView.getHeight() > restrainHeight) {
                ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
                layoutParams.height = restrainHeight;
                contentView.setLayoutParams(layoutParams);
            }
        });
    }

    /**
     * View 弹框
     *
     * @param context
     * @param view
     */
    public static void showViewDialog(Context context, View view) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(view)
                .gravity(Gravity.BOTTOM)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .contentAnimator(new DialogLayer.AnimatorCreator() {
                    @Override
                    public Animator createInAnimator(View content) {
                        return AnimatorHelper.createBottomInAnim(content);
                    }

                    @Override
                    public Animator createOutAnimator(View content) {
                        return AnimatorHelper.createBottomOutAnim(content);
                    }
                }).show();
    }

    public static void showPicCaptureDialog(PhotoBean mPhotoBean, int requestPhotoCapture, int requestPhotoAlbum) {
        DialogUtils.showBottomDialog(
                NavigationController.getInstance().getCurrentActivity(),
                Arrays.asList(new TypeModel("11", "拍照"),
                        new TypeModel("12", "相册")),
                position -> {
                    switch (position) {
                        case 0:
                            PhotoUtil.takePicture(NavigationController.getInstance().getCurrentActivity(), mPhotoBean.getUri(), requestPhotoCapture);
                            break;
                        case 1:
                            PhotoUtil.openPic(NavigationController.getInstance().getCurrentActivity(), requestPhotoAlbum);
                            break;
                        default:
                            break;
                    }
                });
    }

    /**
     * 自定义布局弹框
     *
     * @param context
     * @param contentView
     * @param gravity
     */
    public static DialogLayer showViewDialog(Context context, View contentView, int gravity) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(contentView)
                .gravity(gravity)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .show();
        return mDialogLayer;
    }

    /**
     * 自定义布局弹框
     *
     * @param context
     * @param layoutId
     * @param gravity
     */
    public static DialogLayer showViewDialog(Context context, int layoutId, int gravity) {
        closeDialog();
        mDialogLayer = AnyLayer.dialog(context);
        fitKeyboard(context, mDialogLayer);
        mDialogLayer.contentView(layoutId)
                .gravity(gravity)
                .backgroundColorRes(R.color.dialog_dark_bg)
                .cancelableOnClickKeyBack(false)
                .cancelableOnTouchOutside(false)
                .show();
        return mDialogLayer;
    }


    public static void showDateSelectDialog(BaseActivity activity, TextView tvDate, String title, boolean showCustom,
                                            String customText, OnDateSetListener dateSetListener, OnDateCustomListener onDateCustomListener) {
        DateScrollerDialog.Builder builder = new DateScrollerDialog.Builder();
        builder.hideHM().setTitleStringId(title).setCallback(dateSetListener);
        if (showCustom) {
            builder.showCustom().setCustomCallback(onDateCustomListener);
        }
        builder.build().show(activity.getSupportFragmentManager(), "");
    }

    public static void showDateSelectDialog(BaseActivity activity, TextView tvDate, String title, boolean showAlways) {
        DateScrollerDialog.Builder builder = new DateScrollerDialog.Builder();
        builder.hideHM().setTitleStringId(title).setCallback(new OnDateSetListener() {
            @Override
            public void onDateSet(DateScrollerDialog timePickerView, long milliseconds) {
                tvDate.setText(new SimpleDateFormat("yyyy-MM-dd").format(new Date(milliseconds)));
            }
        });
        if (showAlways) {
            builder.showCustom().setCustomCallback(new OnDateCustomListener() {
                @Override
                public void onDateCustom(String hint) {
                    tvDate.setText(Constants.LONG_TERM);
                }
            });
        }
        builder.build().show(activity.getSupportFragmentManager(), "");
    }

    /**
     * 关闭loading提示框
     */
    public static void closeDialog() {
        if (mDialogLayer != null) {
            mDialogLayer.dismiss();
            if (mDialogLayer.getViewManager() != null)
                mDialogLayer.getViewManager().detach();
        }
    }

    public static boolean isShowing() {
        if (mDialogLayer != null) {
            return mDialogLayer.isShow();
        }
        return false;
    }

    public interface DialogClickListener {
        void onConfirmClick(View view);

        void onCancelClick();
    }

    //适配软键盘的操作
    private static void fitKeyboard(Context context, DialogLayer dialogLayer) {
        if (context != null && context instanceof Activity) {
            Activity activity = (Activity) context;
            KeyBoardUtils.hideSoftKeyboard(activity);
            activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            dialogLayer.onVisibleChangeListener(new Layer.OnVisibleChangeListener() {
                @Override
                public void onShow(Layer layer) {
                }

                @Override
                public void onDismiss(Layer layer) {
                    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
                }
            });
        }
    }
}
